package com.yangyouli.unity_demo_server.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.yangyouli.unity_demo_server.annotation.Inject;
import com.yangyouli.unity_demo_server.annotation.ResponseClass;
import com.yangyouli.unity_demo_server.annotation.ResponseMethod;
import com.yangyouli.unity_demo_server.server.Client;
import com.yangyouli.unity_demo_server.server.RoomObj;
import com.yangyouli.unity_demo_server.server.serializeModel.Room;
import com.yangyouli.unity_demo_server.server.serializeModel.RoomList;
import com.yangyouli.unity_demo_server.service.RoomService;
import com.yangyouli.unity_demo_server.service.UserService;
import com.yangyouli.unity_demo_server.util.ThreadLocalHelper;

@ResponseClass("room")
public class RoomController {
	
	@Inject
	private RoomService roomService;
	@Inject
	private UserService userService;
	
	Logger log = Logger.getLogger(RoomController.class);
	
	/**
	 * 创建房间，并返回房间对象
	 * @return
	 */
	@ResponseMethod("createRoom")
	public String createRoom (String data) {
		Client thisClient = ThreadLocalHelper.getClient();
		int roomId = thisClient.getServer().createRoom(thisClient);
		if (roomId == -1) return "401";
		return JSONObject.toJSONString(roomService.getByRoomObj(String.valueOf(roomId)));
	}
	
	/**
	 * 根据房间 id 查找房间 
	 * @param data 房间 id
	 * @return
	 */
	@ResponseMethod("getRoom")
	public String getRoom (String data) {
		Room room = roomService.getByRoomObj(data);
		if (room == null) {
			log.info("房间号为" + data + "的房间不存在");
			return "0";
		}
		return JSONObject.toJSONString(room);
	}
	
	/**
	 * 根据传来的 roomList 的 currentPage 和 perPageMaxRoom 传过去指定页面的房间列表信息
	 * @param data
	 * @return
	 */
	@ResponseMethod("getRoomList")
	public String getRoomList (String data) {
		Client thisClient = ThreadLocalHelper.getClient();
		RoomList roomList = JSONObject.parseObject(data, RoomList.class);
		List<RoomObj> roomObjList = thisClient.getServer().getRoomObjs();
		// 设置最大页码
		int maxPage = (roomObjList.size() + roomList.getPerPageMaxRoom() - 1) / roomList.getPerPageMaxRoom();
		roomList.setMaxPage(maxPage == 0 ? 1 : maxPage);
		// 得到 currentPage
		int currentPage = roomList.getCurrentPage();
		if (currentPage < 1) roomList.setCurrentPage(1);
		if (currentPage > roomList.getMaxPage()) roomList.setCurrentPage(roomList.getMaxPage());
		// 根据分页计算取列表中的第几个到第几个元素
		int startIndex = (roomList.getCurrentPage() - 1) * roomList.getPerPageMaxRoom();
		// 结束点索引（不包括 endIndex）
		int endIndex = startIndex + roomList.getPerPageMaxRoom();
		if (endIndex > roomObjList.size()) endIndex = roomObjList.size();
		
		roomList.setRoom(new ArrayList<Room>());
		for (int i = startIndex; i < endIndex; i++) {
			roomList.getRoom().add(roomService.getByRoomObj(roomObjList.get(i)));
		}
		return JSONObject.toJSONString(roomList);
	}

	/**
	 * 某个客户端加入房间，data 为房间 id
	 * @param data
	 * @return -1 房间被解散了 0 人数满了 1加入成功
	 */
	@ResponseMethod("joinRoom")
	public String joinRoom (String data) {
		Client client = ThreadLocalHelper.getClient();
		int successfulFlag = client.getServer().joinRoom(data, client);
		return String.valueOf(successfulFlag);
	}
	
	/**
	 * 广播刷新房间内所有玩家的列表
	 * @param data
	 * @return
	 */
	@ResponseMethod("refresh")
	public String refresh (String data) {
		Client client = ThreadLocalHelper.getClient();
		return JSONObject.toJSONString(roomService.getByRoomObj(client.getRoomObj()));
	}
	
	/**
	 * 退出房间
	 * @return 退出的玩家的id
	 */
	@ResponseMethod("exit")
	public void exit (String data) {
		Client client = ThreadLocalHelper.getClient();
		String returnValue = client.getUserId() + "";
		// 退出房间不在能发送消息给其他人，用其他的方式发送
		RoomObj roomObj = client.getRoomObj();
		ThreadLocalHelper.delayResponse(returnValue, roomObj.getMaster());
		ThreadLocalHelper.delayResponse(returnValue, roomObj.getClients());
		client.getServer().removePlayerFromRoom(client);
	}
	
	/**
	 * 游戏结束返回大厅而退出房间
	 * 发送給客户端的消息为:下线的用户 id-用户名
	 * @param data
	 */
	@ResponseMethod("forBackExit")
	public void forBackExit (String data) {
		Client client = ThreadLocalHelper.getClient();
		String returnValue = client.getUserId() + "-" + userService.findById(client.getUserId()).getNickname();
		// 退出房间不在能发送消息给其他人，用其他的方式发送
		RoomObj roomObj = client.getRoomObj();
		ThreadLocalHelper.delayResponse(returnValue, roomObj.getMaster());
		ThreadLocalHelper.delayResponse(returnValue, roomObj.getClients());
		client.getServer().removePlayerFromRoom(client);
	}
	
	/**
	 * 广播到房间内的所有玩家，开始游戏
	 * @param data
	 * @return
	 */
	@ResponseMethod("startGame")
	public String startGame (String data) 
	{
		Client client = ThreadLocalHelper.getClient();
		// 初始化房间内所有玩家的结算的经验金钱为0
		/*RoomObj roomObj = client.getRoomObj();
		List<Client> clients = roomObj.getClientsAndMaster();
		for (Client c : clients) {
			c.setAddExp(0);
			c.setAddMoney(0);
		}*/
		
		client.getRoomObj().setStart(true);
		return "1";
	}
	
	@ResponseMethod("changeMaxPeople")
	public String changeMaxPeople (String data) {
		RoomObj roomObj = ThreadLocalHelper.getClient().getRoomObj();
		roomObj.setMaxPeople(Integer.valueOf(data));
		return JSONObject.toJSONString(roomService.getByRoomObj(roomObj));
	}
	
	@ResponseMethod("changeGameMode")
	public String changeGameMode (String data) {
		RoomObj roomObj = ThreadLocalHelper.getClient().getRoomObj();
		roomObj.setMode(Integer.valueOf(data));
		return JSONObject.toJSONString(roomService.getByRoomObj(roomObj));
	}
	
	@ResponseMethod("kickOut")
	public String kickOut (String data) {
		Client c = ThreadLocalHelper.getClient();
		RoomObj roomObj = c.getRoomObj();
		Client removedUser = roomObj.getClientByUserId(Integer.valueOf(data));
		roomObj.removeClient(removedUser);
		ThreadLocalHelper.delayResponse(data, removedUser);
		return data;
	}
}
